package com.wumai.modernguilib.panel;

import com.mojang.blaze3d.matrix.MatrixStack;
import com.wumai.modernguilib.component.BaseComponent;
import com.wumai.modernguilib.utils.MathHelper;
import net.minecraft.client.gui.AbstractGui;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class GridView extends BaseView {
    private int columns;
    private int rows;
    private float[] columnWidths;  // 每列的宽度权重
    private float[] rowHeights;     // 每行的高度权重
    private float horizontalSpacing = 0.01f; // 水平间距 (NDC坐标)
    private float verticalSpacing = 0.01f;   // 垂直间距 (NDC坐标)
    private Map<BaseComponent, int[]> componentGridPositions = new HashMap<>(); // 存储组件的网格位置
    private Map<String, Integer> cellBackgroundColors = new HashMap<>(); // 存储每个格子的背景色
    private int defaultCellBackgroundColor = 0x00000000; // 默认格子背景色（透明）

    public GridView(int columns, int rows) {
        // 默认构造函数，不指定位置和大小，将自动填充屏幕
        super(0, 0, 0, 0); // 使用0值，将在渲染时自动设置
        this.columns = columns;
        this.rows = rows;
        this.columnWidths = new float[columns];
        this.rowHeights = new float[rows];
        
        // 初始化默认列宽和行高为0，将在布局时计算
        Arrays.fill(columnWidths, 0);
        Arrays.fill(rowHeights, 0);
    }

    /**
     * 绘制每个格子的背景色
     */
    private void renderCellBackgrounds(MatrixStack matrixStack) {
        float currentY = y + verticalSpacing;
        for (int row = 0; row < rows; row++) {
            float currentX = x + horizontalSpacing;
            float cellHeight = rowHeights[row];
            for (int col = 0; col < columns; col++) {
                float cellWidth = columnWidths[col];
                
                // 获取格子背景色
                String cellKey = col + "," + row;
                int backgroundColor = cellBackgroundColors.getOrDefault(cellKey, defaultCellBackgroundColor);
                
                // 如果有背景色则绘制
                if ((backgroundColor & 0xFF000000) != 0) { // 检查alpha通道
                    int pixelCellX = (int) ((currentX + 1.0f) * getCurrentScreenWidth() / 2.0f);
                    int pixelCellY = (int) ((currentY + 1.0f) * getCurrentScreenHeight() / 2.0f);
                    int pixelCellWidth = (int) (cellWidth * getCurrentScreenWidth() / 2.0f);
                    int pixelCellHeight = (int) (cellHeight * getCurrentScreenHeight() / 2.0f);
                    
                    AbstractGui.fill(matrixStack, pixelCellX, pixelCellY, pixelCellX + pixelCellWidth, pixelCellY + pixelCellHeight, backgroundColor);
                }
                
                currentX += cellWidth + horizontalSpacing;
            }
            currentY += cellHeight + verticalSpacing;
        }
    }

    @Override
    protected void onChildAdded(BaseComponent component) {
        // 当子组件通过addChild添加时，需要重新计算布局
    }

    public void addChild(BaseComponent component, int column, int row) {
        if (column >= 0 && column < columns && row >= 0 && row < rows) {
            // 存储组件应该放置的网格位置信息
            componentGridPositions.put(component, new int[]{column, row});
        } else {
            throw new IllegalArgumentException("Invalid column or row index.");
        }
        super.addChild(component);
    }

    public void addChild(BaseView component, int column, int row) {
        if (column >= 0 && column < columns && row >= 0 && row < rows) {
            // 存储组件应该放置的网格位置信息
            componentGridPositions.put(component, new int[]{column, row});
        } else {
            throw new IllegalArgumentException("Invalid column or row index.");
        }
        super.addChild(component);
    }

    @Override
    protected void renderContent(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {

    }

    @Override
    protected void renderBackground(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
        // 绘制半透明背景
        // AbstractGui.fill(matrixStack, x, y, x + width, y + height, 0x80000000);

        // 绘制每个格子的背景色
        renderCellBackgrounds(matrixStack);

        // 绘制边框
        AbstractGui.fill(matrixStack, x, y, x + width, y + 1, 0xFFFFFFFF); // 上边框
        AbstractGui.fill(matrixStack, x, y + height - 1, x + width, y + height, 0xFFFFFFFF); // 下边框
        AbstractGui.fill(matrixStack, x, y, x + 1, y + height, 0xFFFFFFFF); // 左边框
        AbstractGui.fill(matrixStack, x + width - 1, y, x + width, y + height, 0xFFFFFFFF); // 右边框
    }

    // 更新该组件下的子组件布局，这个方法用于更新所有子组件，和addChild不同，
    // 仅仅加入一个子组件，只需更新那一个子组件
    public void updateLayout() {
        
        // 更新列宽和行高
        int availableWidth = width - (int)(columns * horizontalSpacing * getCurrentScreenWidth() * 2);
        int availableHeight = height - (int)(rows * verticalSpacing * getCurrentScreenHeight() * 2);
        
        // 如果列宽或行高未设置，平均分配
        boolean columnWidthsSet = false;
        for (float width : columnWidths) {
            if (width > 0) {
                columnWidthsSet = true;
                break;
            }
        }
        
        boolean rowHeightsSet = false;
        for (float height : rowHeights) {
            if (height > 0) {
                rowHeightsSet = true;
                break;
            }
        }
        
        if (!columnWidthsSet) {
            Arrays.fill(columnWidths, (int)(availableWidth / columns));
        }
        
        if (!rowHeightsSet) {
            Arrays.fill(rowHeights, (int)(availableHeight / rows));
        }

        float totalColumnWidth = MathHelper.sum(columnWidths);
        float totalRowHeight = MathHelper.sum(rowHeights);

        // 根据存储的网格位置将子组件放置到网格中
        for (Map.Entry<BaseComponent, int[]> entry : componentGridPositions.entrySet()) {
            BaseComponent component = entry.getKey();
            int[] gridPos = entry.getValue();
            int col = gridPos[0];
            int row = gridPos[1];

            // 调整组件位置和大小以适应网格单元
            component.setX(this.x + (int)((col * 2 + 1) * horizontalSpacing * getCurrentScreenWidth()) + (int)(MathHelper.sum(columnWidths, 0, col) / totalColumnWidth * availableWidth));
            component.setY(this.y + (int)((row * 2 + 1) * verticalSpacing * getCurrentScreenHeight()) + (int)(MathHelper.sum(rowHeights, 0, row) / totalRowHeight * availableHeight));
            component.setWidth((int) (availableWidth * (columnWidths[col] / totalColumnWidth)));
            component.setHeight((int) (availableHeight * (rowHeights[row] / totalRowHeight)));
        }
    }

    // 设置指定列的宽度
    public void setColumnWidth(int column, int width) {
        if (column >= 0 && column < columns) {
            this.columnWidths[column] = width;
        }
    }
    
    // 设置指定行的高度
    public void setRowHeight(int row, int height) {
        if (row >= 0 && row < rows) {
            this.rowHeights[row] = height;
        }
    }
    
    // 批量设置列宽度
    public void setColumnWidths(float... widths) {
        if (widths.length == columns) {
            System.arraycopy(widths, 0, columnWidths, 0, columns);
        }
    }
    
    // 批量设置行高度
    public void setRowHeights(float... heights) {
        if (heights.length == rows) {
            System.arraycopy(heights, 0, rowHeights, 0, rows);
        }
    }
    
    // 设置指定格子的背景色
    public void setCellBackgroundColor(int column, int row, int color) {
        if (column >= 0 && column < columns && row >= 0 && row < rows) {
            String cellKey = column + "," + row;
            cellBackgroundColors.put(cellKey, color);
        }
    }
    
    // 设置默认格子背景色
    public void setDefaultCellBackgroundColor(int color) {
        this.defaultCellBackgroundColor = color;
    }
    
    // 获取指定格子的背景色
    public int getCellBackgroundColor(int column, int row) {
        String cellKey = column + "," + row;
        return cellBackgroundColors.getOrDefault(cellKey, defaultCellBackgroundColor);
    }
    
    // 获取默认格子背景色
    public int getDefaultCellBackgroundColor() {
        return defaultCellBackgroundColor;
    }
    
    // 获取指定列的宽度
    public float getColumnWidth(int column) {
        if (column >= 0 && column < columns) {
            return columnWidths[column];
        }
        return 0;
    }
    
    // 获取指定行的高度
    public float getRowHeight(int row) {
        if (row >= 0 && row < rows) {
            return rowHeights[row];
        }
        return 0;
    }

    public int getColumns() {
        return columns;
    }

    public int getRows() {
        return rows;
    }
    
    public float getHorizontalSpacing() {
        return horizontalSpacing;
    }
    
    public void setHorizontalSpacing(float horizontalSpacing) {
        this.horizontalSpacing = horizontalSpacing;
    }
    
    public float getVerticalSpacing() {
        return verticalSpacing;
    }
    
    public void setVerticalSpacing(float verticalSpacing) {
        this.verticalSpacing = verticalSpacing;
    }
}